package fr.nts.framework.front.security.service.impl;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import fr.nts.framework.database.jpa.dao.SecurityUserDao;
import fr.nts.framework.database.jpa.model.security.SecurityUser;
import fr.nts.framework.database.jpa.transaction.JPAReadonlyTransaction;
import fr.nts.framework.front.security.service.SimpleUserService;
import fr.nts.framework.front.security.service.exception.BadAuthentificationException;
import fr.nts.framework.front.security.service.exception.BadLoginException;

/**
 * Implémentation du service lié à la manipulation des utilisateurs d'application NTS.
 * 
 * @author sco
 * @version 1.0.0
 */
@Component("simpleUserService")
public class SimpleUserServiceImpl implements SimpleUserService{

	protected static final Logger log = LoggerFactory.getLogger(SimpleUserServiceImpl.class);
	  
	@Resource
	private SecurityUserDao userDao;
	
	/*
	 * (non-Javadoc)
	 * @see fr.nts.framework.front.security.service.NTSUserService#load(java.lang.String)
	 */
	@Override
	@JPAReadonlyTransaction
	public SecurityUser load(final String username) throws BadLoginException{
		SecurityUser user = userDao.findByLogin(username);
		
		if(user == null){
			throw new BadLoginException();
		}
		
		return user;
	}

	
	/*
	 * (non-Javadoc)
	 * @see fr.nts.framework.front.security.service.NTSUserService#authentification(java.lang.String, java.lang.String)
	 */
	@Override
	@JPAReadonlyTransaction
	public SecurityUser authentification(final String username, 
			                             final String password) throws BadAuthentificationException{
		SecurityUser user = userDao.findByLoginAndPassword(username, 
				                                           password);
		
		if(user == null){
			log.info("L'utilisateur avec le couple login password: [{}/{}] n'existe pas en base de données.", username, password);
			throw new BadAuthentificationException();
		}
		
		return user;
	}

}